<template>
  <div>
    <base-table
      :tableData="pageData"
      :page.sync="pageQuery"
      :cols="roleTableColumn"
      v-loading="tableLoading"
      element-loading-text="加载中"
    >
      <template v-slot:header>
        <div class="header">
          <!-- <el-input
            placeholder="请输入底图名"
            @input="fetchData"
            v-model.trim="pageQuery.key"
            class="handle-input mr10"
          >
            <template #append>
              <el-button @click="fetchData"> 搜索 </el-button>
            </template>
          </el-input> -->
          <el-input
            placeholder="请输入底图名"
            v-model.trim="pageQuery.key"
            suffix-icon="el-icon-search"
            style="width: 250px"
            @input="fetchData"
          >
          </el-input>
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd"
            >新增底图</el-button
          >
        </div>
      </template>
      <template v-slot:operation>
        <el-table-column label="缩略图" align="center">
          <template v-slot="scope">
            <img
              @click="handlePictureCardPreview(scope.row.fileUrl)"
              :src="scope.row.fileUrl"
              class="view-img"
              alt=""
            />
          </template>
        </el-table-column>
        <el-table-column label="服务地址" align="center">
          <template v-slot="scope">
            <a :href="scope.row.mapUrl" target="_blank">
              <el-button type="text">{{ scope.row.mapUrl }}</el-button>
            </a>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center">
          <template v-slot="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center">
          <template v-slot="scope">
            <span>{{ scope.row.updateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否为默认" align="center" width="100">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.isDefault"
              :disabled="scope.row.isDefault === 1"
              @click.native="handleSwitch(scope.row)"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-button type="text" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="text" @click="handleDel(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </template>
    </base-table>
    <el-dialog
      :title="title"
      :visible.sync="visible"
      width="30%"
      @closed="closeDialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addFormRef"
        :model="basemapForm"
        label-width="80px"
        :rules="mapFormRules"
      >
        <el-form-item label="底图名" prop="mapName">
          <el-input v-model.trim="basemapForm.mapName"></el-input>
        </el-form-item>
        <el-form-item label="底图地址" prop="mapUrl">
          <el-input v-model.trim="basemapForm.mapUrl"></el-input>
        </el-form-item>
        <el-form-item label="是否默认" prop="isDefault">
          <el-switch
            v-model="basemapForm.isDefault"
            :active-value="1"
            :inactive-value="0"
            :disabled="basemapForm.isDefault === 1"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="缩略图">
          <el-upload
            :action="uploadUrl"
            list-type="picture-card"
            :limit="1"
            :file-list="fileList"
            :on-success="uploaded"
            :on-exceed="handleExceed"
            :before-upload="onBeforeUpload"
            :headers="{
              'AUTH-TOKEN': AUTH_TOKEN,
            }"
            ref="uploadRef"
            accept=".png,.jpeg,.jpg"
          >
            <i slot="default" class="el-icon-plus edit-upload"></i>
            <div slot="file" slot-scope="{ file }">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file.url)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="confirmAddMap">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import baseTable from './compoents/baseTable.vue'
import { getBasemap, uploadUrl, addMap, editMap, delMap } from '@/api/basemap'
export default {
  name: 'basemap',
  components: {
    baseTable,
  },
  data() {
    return {
      mapList: [],
      pageQuery: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
        key: '',
      },
      roleTableColumn: [
        {
          label: '底图名称',
          prop: 'mapName',
          width: '30',
        },
      ],
      tableLoading: false,
      title: '',
      visible: false,
      basemapForm: {
        mapName: '',
        mapUrl: '',
        isDefault: 0,
        serviceOrderIndex: 1,
        baseOrderIndex: 1,
        fileId: undefined,
      },
      mapFormRules: {
        mapName: [
          {
            required: true,
            message: '请输入底图名称',
            trigger: ['blur', 'change'],
          },
        ],
        mapUrl: [
          {
            required: true,
            message: '请输入底图地址',
            trigger: ['blur', 'change'],
          },
        ],
      },
      fileList: [],
      uploadUrl,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      AUTH_TOKEN: null,
    }
  },
  mounted() {
    const user = JSON.parse(window.localStorage.getItem('user'))
    const token = user && user.token
    if (token) {
      this.AUTH_TOKEN = token
    }
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.tableLoading = true
      getBasemap(this.pageQuery.key).then((res) => {
        if (res.success) {
          console.log(res)
          //如果默认的被删除，则将默认改为第一个
          // if (res.data.list.every((item) => item.isDefault === 0)) {
          //   res.data[0].isDefault = 1
          // }
          this.mapList = res.data.list
          this.pageQuery.pageIndex = 1
          this.pageQuery.total = res.data.count
          this.tableLoading = false
        }
      })
    },
    handleAdd() {
      this.title = '新增底图'
      this.visible = true
      this.fileList = []
      this.basemapForm = {
        mapName: '',
        mapUrl: '',
        isDefault: 0,
        serviceOrderIndex: 1,
        baseOrderIndex: 1,
        fileId: undefined,
      }
      if (this.$refs.addFormRef) {
        this.$refs.uploadRef.clearFiles()
        this.$refs.addFormRef.resetFields()
      }
      document.querySelector(
        '.edit-upload'
      ).parentElement.parentElement.className = 'display-block'
    },
    handleEdit(row) {
      console.log('row :>> ', row)
      this.basemapForm = {
        ...row,
      }
      this.title = '编辑底图'
      this.visible = true
      this.fileList = [
        {
          name: row.fileName,
          url: row.fileUrl,
          fileId: row.fileId,
          isUploaded: true,
        },
      ]
      this.$nextTick(() => {
        document.querySelector(
          '.edit-upload'
        ).parentElement.parentElement.className = 'display-none'
      })
    },
    handleDel(row) {
      console.log('row :>> ', row)
      this.$confirm(`此操作将删除${row.mapName}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          delMap(row.pkid).then((res) => {
            if (res.success) {
              this.$message.success('删除成功')
              this.fetchData()
            } else {
              this.$message.error('删除失败')
            }
          })
        })
        .catch((e) => {
          console.log('e :>> ', e)
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    confirmAddMap() {
      if (!this.basemapForm.pkid) {
        this.$refs.addFormRef.validate((valid) => {
          if (valid) {
            if (this.title === '新增底图') {
              addMap({ ...this.basemapForm }).then((res) => {
                if (res.success) {
                  this.$message.success('新增成功')
                  this.closeDialog()
                  this.fetchData()
                } else {
                  this.$message.error('新增失败')
                }
              })
            } else {
              this.handleSwitch(this.basemapForm)
            }
          }
        })
      } else {
        editMap(this.basemapForm.pkid, this.basemapForm).then((res) => {
          if (res.success) {
            this.$message.success('修改成功')
            this.closeDialog()
            this.fetchData()
          } else {
            this.$message.error('修改失败')
          }
        })
      }
    },
    handleSwitch(row) {
      //点击默认打开的那个开关不做任何操作
      if (this.pageData.filter((item) => item.isDefault === 1).length > 1) {
        row.baseOrderIndex = 1
        editMap(row.pkid, { ...row }).then((res) => {
          if (res.success) {
            this.$message.success('修改成功')
            this.closeDialog()
            this.fetchData()
          } else {
            this.$message.error('修改失败')
          }
        })
      }
    },
    closeDialog() {
      this.title = ''
      this.visible = false
      this.fileList = []
      if (this.$refs.uploadRef) {
        this.$refs.uploadRef.clearFiles()
        this.$refs.addFormRef.resetFields()
      }
    },
    handlePictureCardPreview(url) {
      this.dialogImageUrl = url
      this.dialogVisible = true
    },
    handleRemove(file) {
      this.fileList = this.fileList.filter((i) => i.name !== file.name)
      if (this.fileList.length === 0) {
        document.querySelector(
          '.edit-upload'
        ).parentElement.parentElement.className = 'display-block'
      } else {
        document.querySelector(
          '.edit-upload'
        ).parentElement.parentElement.className = 'display-none'
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    uploaded(response, file, fileList) {
      this.fileList = fileList
    },
    onBeforeUpload() {
      // if (this.fileList.length === 0) {
      //   console.dir((document.querySelector(".edit-upload").parentElement.parentElement.className = "display-block"));
      // } else {
      // }
      console.log('1 :>> ', 1)
      document.querySelector(
        '.edit-upload'
      ).parentElement.parentElement.className = 'display-none'
      return true
    },
  },
  computed: {
    pageData() {
      return this.mapList.slice(
        (this.pageQuery.pageIndex - 1) * this.pageQuery.pageSize,
        this.pageQuery.pageIndex * this.pageQuery.pageSize
      )
    },
  },
  watch: {
    fileList(val) {
      if (val.length) {
        this.basemapForm.fileId = val[0].isUploaded
          ? val[0].fileId
          : val[0].response.data
      } else {
        this.basemapForm.fileId = undefined
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.header {
  display: flex;
  justify-content: space-between;
}
.handle-input {
  width: 300px;
}
.view-img {
  height: 50px;
  cursor: pointer;
}
.center {
  display: flex;
  align-items: center;
  height: 40px;
}
::v-deep .el-upload-list__item {
  transition: none;
}
.display-none {
  ::v-deep .el-upload.el-upload--picture-card {
    display: none;
  }
}
.display-block {
  ::v-deep .el-upload.el-upload--picture-card {
    display: inline-block;
  }
}
</style>
